package com.eling.elcms.system.service.impl;

import com.eling.elcms.community.model.Building;
import com.eling.elcms.core.AppContext;
import com.eling.elcms.core.dao.hibernate.CriteriaUtils;
import com.eling.elcms.core.dao.hibernate.ICriteriaEnhancer;
import com.eling.elcms.core.dao.hibernate.IQueryCondition;
import com.eling.elcms.system.model.ElcmsUser;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import java.util.HashSet;
import java.util.Set;

/**
 * 自动附加楼权限语句的查询增强器，参数格式为楼实体相对于本实体的完整路径，比如：会员的参数配置为“memberSigning.room.building”
 * 
 * @author KEN
 *
 */
public class BuildingPrivilegeCriteriaEnhancer implements ICriteriaEnhancer {
	private String buildingPath;

	@Override
	public void init(String parameter) {
		buildingPath = parameter;
	}

	@Override
	public Criteria enhance(Criteria criteria, Object cond) {
		// 后台任务执行时，使用匿名用户，不附加楼权限
		if (AppContext.anonymous == AppContext.curUser()) {
			return criteria;
		}
		if (cond instanceof IQueryCondition) {
			// 如果不进行权限校验，则不附加楼权限
			IQueryCondition qc = (IQueryCondition) cond;
			if (Boolean.FALSE.equals(qc.getValidatePrivilege())) {
				return criteria;
			}
		}
		Set<Long> pkBuildings = new HashSet<>();
		// 增加一个不存在的楼宇pk，防止没有楼宇权限时sql执行报错
		pkBuildings.add(-99L);
		for (Building building : ((ElcmsUser) AppContext.curUser()).getBuildings()) {
			pkBuildings.add(building.getPkBuilding());
		}

		CriteriaUtils.getOrCreateCriteria(criteria, buildingPath).add(Restrictions.in("pkBuilding", pkBuildings));
		return criteria;
	}

}
